package com.base.andlangui.weight

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.base.andlangui.R

/**
 * 自定义Toast
 * 1.文字toast
 * 2.图文toastImg
 */
object ToastKt {
    private var mToast: Toast? = null

    /**
     *  如果 mToast 没有初始化, 就创建一个 Toast, 并赋值
     *  否则就直接显示
     */
    private fun <T : Context> showToast(context: T, message: String?, duration: Int) {
        mToast?.let {
            it.duration = duration
            it.setText(message)
            it.show()
        } ?: Toast.makeText(context.applicationContext, message, duration).apply {
            mToast = this
            show()
        }
    }

    private fun <T : Context> showImgToast(context: T, message: String?, duration: Int) {
        val toast = Toast(context)
        toast!!.duration = duration
        //设置Toast的显示位置
        toast!!.setGravity(Gravity.CENTER, 0, 0)
        //创建一个ImageView
        val image = ImageView(context)
        image.setImageResource(R.mipmap.icon_white_error)
        image.scaleType= ImageView.ScaleType.FIT_CENTER
        //创建一个LinearLayout容器
        val ll = LinearLayout(context)
        ll.setBackgroundResource(R.drawable.bg_rect_black_8dp)
        ll.setPadding(15,30,15,30);
        //想LinearLayout中添加图片、原有的View
        ll.addView(image)
        //创建一个ImageView
        val textView = TextView(context)
        textView.text="  $message"
        //设置文本框字体号的大小和字体颜色
        textView.setTextSize(15f)
        textView.setTextColor(Color.WHITE)
        ll.addView(textView)
        //设置Toast显示自定义View
        toast!!.setView(ll)
        //设置Toast的显示时间
        toast!!.setDuration(Toast.LENGTH_SHORT)
        toast!!.show()
    }

    @SuppressLint("ShowToast")
    fun init(context: Context) {
        mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT)
    }

    fun show(message: String) {
        mToast?.apply { setText(message) }?.show()
    }


    /**
     *  防止重复 showToast 显示
     *  如果 mToast不为空 就显示, 否则就创建新的 mToast
     */
    fun Context.toast(message: String?, duration: Int = Toast.LENGTH_SHORT) {
        showToast(this, message, duration)
    }

    fun Fragment.toast(message: String, duration: Int = Toast.LENGTH_SHORT) {
        context?.let { showToast(it, message, duration) }
    }

    fun Context.toastImg(message: String?, duration: Int = Toast.LENGTH_SHORT) {
        showImgToast(this, message, duration)
    }

    fun Fragment.toastImg(message: String, duration: Int = Toast.LENGTH_SHORT) {
        context?.let { showImgToast(it, message, duration) }
    }

}